const express=require('express')
const mysql = require('mysql')
const bodyParser=require('body-parser')
const { v4: uuidv4 } = require('uuid'); 
const nodemailer = require('nodemailer')
const cors = require('cors')
//跨域解决办法


const app=express()

app.use(bodyParser.urlencoded({extended:true}))
app.use(bodyParser.json())
app.use(cors());

app.listen(3000,()=>{
    console.log('服务器，启动！')
})

const conn= mysql.createConnection({
    host:'47.111.80.54',
    user:'root',
    password:'b175de135281bb40',
    port:'3306',
    database:'caipu'
})

conn.connect()
// 提供查询服务
app.post('/login',(req,res)=>{
    let {mobile,password}=req.body
    console.log(mobile,password)
    let sql='select * from login where mobile=? and password=?'
    conn.query(sql,[mobile,password],(err,results)=>{
        if(err){
            console.log(err)
            res.send({code:500,msg:'查询失败'})
        }
        if(results.length){
            res.send({code:200,msg:'查询成功',data:results})
        }
        else{
            res.send({code:400,msg:'用户名或密码错误'})
        }
        console.log(results)
    })
})
app.post('/homepage/peiliao',function(req,res){
    
    const recipeid=req.body.recipeid
    if (!recipeid) {
        return res.status(400).json({
            code: 400,
            message: '缺少recipeid参数'
        });
    }
    const sqlStr=`SELECT r.recipe_id,r.recipe_name,i.ingredient_id,i.ingredient_name FROM recipes r JOIN recipe_ingredients ri ON r.recipe_id = ri.recipe_id JOIN ingredients i ON ri.ingredient_id = i.ingredient_id WHERE r.recipe_id = ?`
    
    console.log(sqlStr)
    conn.query(sqlStr,[recipeid],(err,results)=>{
        if(err){
            return res.status(500).json({ 
                code:500,
                message:err.message 
            })
        }
        res.json({ 
            code:200,
            message:'成功',
            data:results
        })
    })
})
//注册
app.post('/login/zhuce',function(req,res){
    let {mobile,password}=req.body
    let sqlStr='insert into login(mobile,password) value(?,?)'
    conn.query(sqlStr,[mobile,password],(err,results)=>{
        if(err){
            return res.status(500).json({
                code:500,
                message:err.message
            })
        }
        res.json({
            code:200,
            message:'成功',
            data:results
        })
    })
})
// //邮箱验证码发送
const verificationCodes={}
app.post('/send',(req,res)=>{
    const {mobile}=req.body
    if(!/^1\d{10}$/.test(mobile)){
        return res.status(400).json({ code: 400, message: '手机号格式错误' })
    }
  const code = Math.floor(100000 + Math.random() * 900000).toString(); 
  const verificationId = Date.now(); // 用时间戳当唯一 ID

  // 存储验证码（有效期 5 分钟）
  verificationCodes[verificationId] = { code, expiresAt: Date.now() + 5 * 60 * 1000 };

  // 模拟发送：实际开发中替换为短信平台调用
  console.log(`模拟给 ${mobile} 发验证码：${code}（ID: ${verificationId}，5分钟内有效）`);
  res.json({ 
    code: 200, 
    message: '验证码已发送到手机（模拟）', 
    data: { verificationId, code } 
  });
});
app.post('/code', (req, res) => {
    const { verificationId, code } = req.body;
    const stored = verificationCodes[verificationId];
    if (!stored || stored.expiresAt < Date.now()) {
      return res.status(400).json({ code: 400, message: '验证码已过期或无效' });
    }
    if (stored.code !== code) {
      return res.status(400).json({ code: 400, message: '验证码错误' });
    }
    delete verificationCodes[verificationId]; // 验证后销毁
    res.json({ code: 200, message: '验证成功' });
  });

app.post('/login/updata',function(req,res){
    let {mobile,password}=req.body
    let sql='update login set password=? where mobile=?'
    conn.query(sql,[password,mobile],(err,results)=>{
        if(err){
            return res.status(500).json({ 
                code:500,
                message:err.message 
            })
        }
        res.json({ 
            code:200,
            message:'成功',
            data:results
        })
    })
    
    
})